package sapling.web.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sapling.dao.AdminDao;
import sapling.dao.RoleDao;
import sapling.dao.UserDao;
import sapling.model.Admin;
import sapling.model.Role;
import sapling.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by ever on 2016/10/9.
 */
@Controller
@RequestMapping(value = "/admin/role")
public class RoleAction {

    @Autowired
    AdminDao adminDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    UserDao userDao;


    @RequestMapping("")
    public String list(Model model) {
        List<Admin> admins= adminDao.findByUsernameNot("admin");
        model.addAttribute("admin",admins);
        return "redirect:/admin/admin";
    }

    @RequestMapping("/allocation")
    public String allocation(int type,Long id){
        List<Role> roles=new ArrayList<>();
        if(Objects.nonNull(id)){
            Admin admin=adminDao.findOne(id);
            Role role;
            if(1==type){
               role= roleDao.findOneByName("common");
                roles.add(role);
            }else if(2==type){
                role= roleDao.findOneByName("finance");
                roles.add(role);
            }else if(3==type){
                role = roleDao.findOneByName("watcher");
                roles.add(role);
            }
            admin.setRoleList(roles);
            adminDao.save(admin);
        }
        return "redirect:/admin/role";
    }

    @RequestMapping("/user")
    public String user(int type,Long id){
        List<Role> roles=new ArrayList<>();
        if(Objects.nonNull(id)){
            User user=userDao.findOne(id);
            Role role;
            if(1==type){
                role= roleDao.findOneByName("common");
                roles.add(role);
            }else if(2==type){
                role= roleDao.findOneByName("finance");
                roles.add(role);
            }
            user.setRoleList(roles);
            userDao.save(user);
        }
        return "redirect:/admin/appAdmin";
    }
}
